// ==UserScript==
// @name     IndiaChan Update
// @version  1
// @grant    none
// @include https://indiachan.com/*/res/*.html*
// ==/UserScript==

function update() {

    var status = document.getElementById("update-status");

    var url = new URL(window.location.href);
    url.hash = "";
    var json_url = url.href.replace(".html", ".json");

    var existing_posts = document.getElementsByClassName("divPosts")[0].children;
    var after = 0;

    if (existing_posts.length !== 0) {
        after = parseInt(existing_posts[existing_posts.length - 1].id, 10);
    }

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status !== 200) {
                // error
                status.innerText = "error";
                console.log(xhr.status);
                console.log(xhr);
                return;
            }

            response = JSON.parse(xhr.responseText);
            posts = response["posts"];
            status.innerText = "done";
            console.log(posts);
            //status.innerText = xhr.responseText;
            var num_new_posts = 0;
            for (var i = 0; i < posts.length; i++) {
                var r = posts[i];
                if (r["postId"] <= after) {
                    continue;
                }
                num_new_posts++;
                var imagehtml = "";
                if (r['files'].length !== 0) {
                    imagehtml = `<div class="panelUploads">`;
                    for (var j = 0; j < r['files'].length; j++) {
                        var f = r['files'][j]
                        imagehtml += `<figure class="uploadCell">
					<div class="innerUpload t-bgt">
						<a class="imgLink" target="blank" href="${f['path']}" data-filewidth="${f['width']}" data-fileheight="${f['height']}" data-filemime="${f['mime']}">
						<img src="${f['thumb']}"></a>
						<div class="originalNameLink" href="${f['path']}" download="${f['originalName']}">${f['originalName']}</div>
						<div class="uploadDetails hidden"><div class="sizeLabel">${f['size']} bytes</div>
						<div class="nameLink" href="${f['path']}"></div><div class="labelHash">__labelHash_inner__</div><div class="dimensionLabel">${f['width']}x${f['height']}</div>
						</div></div>
				</figure>`
                    }
                    imagehtml += `</div>`
                }

                var posthtml = `<div class="postCell" data-boarduri="g" id=${r['postId']}>
<div class="innerPost"><div class="postTitle"><span class="linkName  noEmailName">anon</span>
<span class="spanId"><span class="labelId" style="background-color: #${r["id"]}" data-id="${r["id"]}" data-count="1" title="1 posts by this user">${r["id"]}</span></span>
<span class="labelCreated" title="Mon Jun 29 2020 02:21:26 GMT+0530 (India Standard Time)" datetime="${r['creation']}" timeago-id="76">6 hours ago</span>
<a class="linkQuote" href="/${response["boardUri"]}/res/${response["threadId"]}.html#q${r["postId"]}">3589</a>
<a class="linkMod btnLink">Mod</a>
<a class="linkSelf" href="/${response["boardUri"]}/res/${response["threadId"]}.html#${r["postId"]}"></a>
<div class="panelBacklinks"></div><input class="deletionCheckBox" type="checkbox" name="g-${response["threadId"]}-${r["postId"]}"></div>
` + imagehtml + `
<div class="divMessage">${r["markdown"]}</div>
<div class="postExtra"><p class="labelOmission"><span></span></p></div><div class="panelBacklinks"></div></div></div>`;

                var div = document.createElement('div');
                div.innerHTML = posthtml.trim();
                document.getElementsByClassName("divPosts")[0].appendChild(div.firstChild);
            }
        }
        status.innerText = "done: " + num_new_posts.toString() + " new";
    }

    xhr.open("GET", json_url, true); // true for asynchronous 
    xhr.send(null);
    status.innerText = "updating..."
}

function add_update_btn() {
    //GM.log("update js loaded");
    var btns = document.getElementsByClassName("divPages")[0];
    var update_btn = document.createElement("a");
    update_btn.id = "update-btn";
    update_btn.href = "javascript:void(0);"
    update_btn.onclick = update;
    update_btn.innerText = "Update";
    btns.appendChild(update_btn);
    var update_status = document.createElement("span");
    update_status.id = "update-status";
    btns.appendChild(update_status);
}

window.addEventListener('load', add_update_btn, false);